package com.blb.zycommunity.config;

import com.blb.zycommunity.service.ISysUserService;
import com.blb.zycommunity.service.IZyOwnerService;
import com.blb.zycommunity.utils.ApplicationContextUtils;
import com.blb.zycommunity.utils.JwtUtils;
import com.blb.zycommunity.utils.RsaUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Slf4j
public class TokenAuthenticationFilter extends BasicAuthenticationFilter {

    /**
     * 请求头名称
     */
    public static final String HEADER = "Authorization";

    //通过IOC容器获得bean对象
    private ISysUserService sysUserService = ApplicationContextUtils
            .getApplicationContext().getBean(ISysUserService.class);

    private IZyOwnerService zyOwnerService = ApplicationContextUtils
            .getApplicationContext().getBean(IZyOwnerService.class);

    public TokenAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    /**
     * 过滤请求和响应
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String uri = request.getRequestURI();
        if(uri.contains("uni-app")){
            //获得请求头中的token
            String token = request.getHeader(HEADER);
            if(token == null){
                throw new RuntimeException("token为空");
            }
            try {
                //解析请求头
                String username = JwtUtils.getUsernameFromToken(token, RsaUtils.publicKey);
                //解析成功就创建令牌，交给security，让请求通信
                List<GrantedAuthority> authorities = zyOwnerService.getAuthoritiesByNickname(username);
                UsernamePasswordAuthenticationToken uToken = new UsernamePasswordAuthenticationToken(username,"",authorities);
                SecurityContextHolder.getContext().setAuthentication(uToken);
            }catch (Exception ex){
                log.error("解析token失败",ex);
            }
            //执行下一个过滤器
            chain.doFilter(request,response);
        }else{
            //获得请求头中的token
            String token = request.getHeader(HEADER);
            if(token == null){
                throw new RuntimeException("token为空");
            }
            try {
                //解析请求头
                String username = JwtUtils.getUsernameFromToken(token, RsaUtils.publicKey);
                //解析成功就创建令牌，交给security，让请求通信
                List<GrantedAuthority> authorities = sysUserService.getAuthoritiesByUsername(username);
                UsernamePasswordAuthenticationToken uToken = new UsernamePasswordAuthenticationToken(username,"",authorities);
                SecurityContextHolder.getContext().setAuthentication(uToken);
            }catch (Exception ex){
                log.error("解析token失败",ex);
            }
            //执行下一个过滤器
            chain.doFilter(request,response);
        }
    }
}